/*=============================================================================*
 *         Copyright(c) 2009-2010, Siemens PLM Software Inc.
 *                          ALL RIGHTS RESERVED

 *  FILENAME : 	ArrayPropertyTableCellEditor.java
 *  PURPOSE  : 	cell editor for ArrayPropertyTable
 *  
 *  HISTORY  :
 *    DATE            VERSION        AUTHOR            NOTE
 *    2009-02-09      V1.0           Tim              Created.    
 *   
 *============================================================================*/

package com.hs.rac.form;

import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.Date;
import java.util.EventObject;
import java.util.Vector;

import javax.swing.AbstractCellEditor;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;

import com.teamcenter.rac.common.TCTypeRenderer;
import com.teamcenter.rac.common.lov.LOVUIComponent;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentListOfValues;
import com.teamcenter.rac.kernel.TCComponentQuery;
import com.teamcenter.rac.kernel.TCComponentQueryType;
import com.teamcenter.rac.kernel.TCDateFormat;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.DateButton;
import com.teamcenter.rac.util.FilterDocument;
import com.teamcenter.rac.util.iTextField;


/**
 * table cell editor for array property
 * @author hex
 *
 */
public class ArrayPropertyTableCellEditor extends AbstractCellEditor
implements TableCellEditor
{
	/** table model */
	protected ArrayPropertyTableModel tm;
	/** text filed cell editor */
	protected iTextField textField;
	/** filter document for text filed */
	protected FilterDocument document;
	/** LOVUIComponent for property has relation lov */
	protected LOVUIComponent lovUIComponent;
	/** date button */
	protected DateButton dateButton;
	/** JComboBox for logical property */
	protected JComboBox logicalSelection;
	/** label */
	protected JLabel label;
	
	protected CustComboBox jcombobox;

	
	/**
	 *  ArrayPropertyTableCellEditor construct
	 * @param session	IMAN session
	 * @param table	table
	 */
    public ArrayPropertyTableCellEditor(TCSession session,JTable table)
    {
    	tm = (ArrayPropertyTableModel)table.getModel();
        String encoding =
            TCSession.getServerEncodingName(session);
        //initialize common swing component
        document = new FilterDocument(32, encoding);
        textField = new iTextField(document, "", 15);
        lovUIComponent = new LOVUIComponent();
        dateButton = new DateButton();
        logicalSelection =
           new JComboBox(new Object[] { Boolean.TRUE, Boolean.FALSE });
        label = new JLabel();
        
        jcombobox=new CustComboBox();
        jcombobox.setEditable(true);
        jcombobox.getEditor().getEditorComponent().addKeyListener(new KeyListener(){

			@Override
			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void keyReleased(KeyEvent e) {
				// TODO Auto-generated method stub
				char   ch   =   e.getKeyChar(); 
				if   (ch   ==   KeyEvent.CHAR_UNDEFINED||Character.isISOControl(ch)) 
					if(ch   !=   KeyEvent.VK_DELETE&&ch   !=   KeyEvent.VK_BACK_SPACE){
						return; 
					}                    
				JTextField jtf=(JTextField)jcombobox.getEditor().getEditorComponent();
				String s= jtf.getText();
				jcombobox.removeAllItems();
				for(Object o:jcombobox.getSourcedata()){
					String so=(String) o;
					if(s==""||s.length()==0){
						jcombobox.addItem(so);
					}else if(so.toLowerCase().startsWith(s.toLowerCase())){
						jcombobox.addItem(so);
					}
				}				
				jcombobox.hidePopup();
				jcombobox.showPopup();
				jtf.select(s.length(), s.length());
				jtf.setText(s);
			}

			@Override
			public void keyTyped(KeyEvent e) {
				// TODO Auto-generated method stub
				
				
			}
        	
        });
    }

    /** current select culumn */
    protected ArrayPropertyTableColumn currentColumn = null;

   /**
    * get value of cell editor
    * @return	value
    */
   public Object getCellEditorValue()
   {
      TCComponentListOfValues lov = null;      
      if(currentColumn == null)
    	  return label.getText();
      try
      {
    	  //get lov of property if property relate lov 
         lov = currentColumn.getProperty().getLOV();
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
      Object obj = null;
      String s;
      if (lov != null)
      {
         obj = lovUIComponent.getText();
         s = obj == null ? "" : obj.toString();
      }
      else
      {
         s = textField.getText();
      }
      //SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
      TCDateFormat dateFormat = new TCDateFormat(currentColumn.getProperty().getTCComponent().getSession());

      switch (currentColumn.getColumnPropertyType())
      {
         case 1 :
            if (s != null && s.length() > 0)
               return new Character(s.charAt(0));
            return new Character('?');
         case 2 :
        	 if(dateButton.getDate()!=null)
        		 return dateFormat.format(dateButton.getDate());
        	 return "";
         case 3 :
            if (s != null && s.length() > 0)
               return new Double(Double.parseDouble(s));
            return new Double(0.0D);
         case 4 :
            if (s != null && s.length() > 0)
               return new Float(Float.parseFloat(s));
            return new Float(0.0);
         case 5 :
            if (s != null && s.length() > 0)
               return new Integer(Integer.parseInt(s));
            return new Integer(0);
         case 6 :
            return logicalSelection.getSelectedItem();
         case 12 :
            return s;
         case 7 :
            if (s != null && s.length() > 0)
               return new Short(Short.parseShort(s));
            return new Short((short) 0);
         case 8 :
            return s;
      }
      return null;
   }

   /**
    *  is celll editable
    *  @param evt	cell editor 's event
    */
   public boolean isCellEditable(EventObject evt)
   {
      if (!super.isCellEditable(evt))
         return false;
      if (evt != null && evt instanceof MouseEvent)
         return ((MouseEvent) evt).getClickCount() >= 2;
      return true;
   }
   
   class CustComboBox extends JComboBox{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Vector sourcedata;

	public Vector getSourcedata() {
		return sourcedata;
	}

	public void setSourcedata(Vector sourcedata) {
		this.sourcedata = sourcedata;
	}
	
	   
   }

@Override
public Component getTableCellEditorComponent(JTable table, Object value,
		boolean isSelected, int row, int column) {
	// TODO Auto-generated method stub

    //currentColumn = tm.getColumn(col);
	   currentColumn = tm.getColumn(table.convertColumnIndexToModel(column));
	   
    String s = value == null ? "" : value.toString();
    //if column is not exist, return label
    if(currentColumn == null)
    {
 	   label.setText(s);
 	   return label;
    }
    try
    {
 	  // System.out.println("P name: " + currentColumn.getProperty().getPropertyName());
 	   //get lov of property if property relate lov 
        TCComponentListOfValues lov = currentColumn.getProperty().getLOV();
      if (lov != null)
      {
         lovUIComponent =
            new LOVUIComponent(
               lov,
               s,
               -1,
               false);
         lovUIComponent.setSelectedValue(value);
         lovUIComponent.setText(s);
         return lovUIComponent;
      }
   }
   catch (Exception e)
   {
      e.printStackTrace();
   }
   //for each column set default swing component editor
	 TCDateFormat tcdateformat = new TCDateFormat((TCSession) currentColumn.getProperty().getTCComponent().getSession());

   switch (currentColumn.getColumnPropertyType())
   {
      case 1 :
         document.setAcceptedChars(null);
         document.setLength(1);
         textField.setText(s);
         return textField;
      case 2 :
     	 if(value!=null){
     		 try {
     			 dateButton.setDate(tcdateformat.parse(value.toString()));
				} catch (ParseException e) {
					e.printStackTrace();
				}
     	 }else{
              dateButton.setDate((Date) null);
     	 }       		 
         return dateButton;
      case 3 :
      case 4 :
         document.setAcceptedChars("0123456789.eE");
         textField.setText(s);
         return textField;
      case 5 :
         document.setAcceptedChars("9876543210");
         textField.setText(s);
         return textField;
      case 6 :
         logicalSelection.setSelectedItem((Boolean) value);
         return logicalSelection;
      case 12 :
         document.setAcceptedChars(null);
         document.setLength(
            currentColumn
               .getProperty()
               .getPropertyDescriptor()
               .getMaxStringLength());
         textField.setText(s);
         return textField;
      case 7 :
         document.setAcceptedChars("1023456789");
         textField.setText(s);
         return textField;
      case 8 :
         document.setAcceptedChars(null);
         document.setLength(
            currentColumn
               .getProperty()
               .getPropertyDescriptor()
               .getMaxStringLength());
         textField.setText(s);
         return textField;
      case 9 :
      case 10 :
      case 11 :
      case 13 :
      case 14 :
         label.setText(s);
         if (value instanceof TCComponent)
         {
            label.setIcon(
               TCTypeRenderer.getIcon((TCComponent) value, false));
         }
         return label;
   }
   return null;

}

}